//
//  ChatInputView.m
//  TestChat
//
//  Created by yull on 14/12/7.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "ChatInputView.h"
#import "UIColor+MethodExt.h"

@implementation ChatInputView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = RGB(236, 236, 236);
        
        self.animated = YES;
        
        [self initButton];
        
        [self initFunctionView];
        
        [self initAudioView];
        
        self.recordAudio = [MUPAudioRecorder sharedInstance];
        //self.recordAudio.delegate = self;
    }
    return self;
}

- (void)initButton
{
    CGFloat buttonWidth = self.height - 5 * 2;
    CGRect rect = CGRectMake(5, 5, buttonWidth, buttonWidth);
    self.buttonInput = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonInput.frame = rect;
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio"] forState:UIControlStateNormal];
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio_selection"] forState:UIControlStateHighlighted];
    [self addSubview:self.buttonInput];
    
    rect = CGRectMake(self.buttonInput.right + 5, 5, 187 + buttonWidth + 5, 36);
    self.buttonAudio = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonAudio.frame =rect;
    self.buttonAudio.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.buttonAudio setTitle:@"按住说话" forState:UIControlStateNormal];
    [self.buttonAudio setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.buttonAudio setBackgroundImage:[[UIImage imageNamed:@"chat_record"] stretchableImageWithLeftCapWidth:2 topCapHeight:2] forState:UIControlStateNormal];
    [self.buttonAudio setBackgroundImage:[[UIImage imageNamed:@"chat_record_selection"] stretchableImageWithLeftCapWidth:2 topCapHeight:2] forState:UIControlStateHighlighted];
    [self addSubview:self.buttonAudio];
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f) {
        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        NSTextStorage *textStorage = [[NSTextStorage alloc] init];
        [textStorage addLayoutManager:layoutManager];
        NSTextContainer *textConainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(187,CGFLOAT_MAX)];
        textConainer.lineBreakMode = NSLineBreakByWordWrapping;
        [layoutManager addTextContainer:textConainer];
        
        self.textViewInput = [[UITextView alloc] initWithFrame:rect textContainer:textConainer];
        
        self.textViewInput.layoutManager.allowsNonContiguousLayout = NO;
    }else {
        self.textViewInput = [[UITextView alloc] initWithFrame:rect];
    }
    self.textViewInput.layer.cornerRadius = 5;
    self.textViewInput.font = [UIFont systemFontOfSize:15];
    self.textViewInput.returnKeyType = UIReturnKeySend;
    self.textViewInput.delegate = self;
    [self addSubview:self.textViewInput];

    rect = CGRectMake(self.buttonAudio.right + 5, 5, buttonWidth, buttonWidth);
    self.buttonOther = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOther.frame = rect;
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other"] forState:UIControlStateNormal];
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other_selection"] forState:UIControlStateHighlighted];
    [self addSubview:self.buttonOther];
    
    [self.buttonOther addTarget:self action:@selector(onOtherButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonInput addTarget:self action:@selector(onInputButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.buttonAudio addTarget:self action:@selector(btnDown:) forControlEvents:UIControlEventTouchDown];//按下触发
    [self.buttonAudio addTarget:self action:@selector(btnUp:) forControlEvents:UIControlEventTouchUpInside];//抬起触发
    [self.buttonAudio addTarget:self action:@selector(btnDragUp:) forControlEvents:UIControlEventTouchDragExit];//拖动触发
    [self.buttonAudio addTarget:self action:@selector(btnDragEnter:) forControlEvents:UIControlEventTouchDragEnter];//重新获得焦点？
    [self.buttonAudio addTarget:self action:@selector(btnTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];//抬起
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self.textViewInput addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)initFunctionView
{
    CGRect rect = CGRectMake(0, self.height, self.width, 215);
    self.functionView = [[ChatFunctionView alloc] initWithFrame:rect];
    [self addSubview:self.functionView];
}

- (void)didMoveToSuperview
{
    if (!self.recordView.superview) {
        [self.superview addSubview:self.recordView];
    }
}

- (void)initAudioView
{
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].applicationFrame);
    CGFloat height = CGRectGetHeight([UIScreen mainScreen].applicationFrame);
    
    self.recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    self.recordView.left = width / 2 - 75;
    self.recordView.top = height / 2 - 110;
    self.recordView.backgroundColor = [UIColor clearColor];
    self.recordView.hidden = YES;
}

- (void)onOtherButtonClicked:(id)sender
{
    if (self.style != ChatInputViewStyleOther) {
        
        self.style = ChatInputViewStyleOther;
        
        self.height = self.topHeight + 215;
        
        self.functionView.top = self.height;
        [self bringSubviewToFront:self.functionView];
        [UIView animateWithDuration:0.25f animations:^{
            self.functionView.top = self.topHeight;
        }];

    }else {
        self.style = ChatInputViewStyleNormal;
    }
}

- (void)onInputButtonClicked:(id)sender
{
    if (self.style != ChatInputViewStyleAudio) {
        self.style = ChatInputViewStyleAudio;
        [UIView animateWithDuration:0.25f animations:^{
            self.height = ChatInputView_Height;
            [self resetButtonFrame];
        }];
    }else {
        self.style = ChatInputViewStyleNormal;
        [UIView animateWithDuration:0.25f animations:^{
            self.height = self.topHeight;
            [self updateButtonFrame];
        }];
        
    }
}

- (void)onKeyboardShow:(NSNotification *)notification
{
    CGRect keyboardFrame = [[notification.userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue];
    self.keyboardHeight = keyboardFrame.size.height;
    
    self.height = self.topHeight + self.keyboardHeight;
    
    self.style = ChatInputViewStyleText;
    
    [UIView animateWithDuration:0.25f animations:^{
        self.functionView.top = self.height;
    }];
    
}

- (void)onKeyboardChange:(NSNotification *)notification
{
    if (self.style == ChatInputViewStyleText) {
        CGRect keyboardFrame = [[notification.userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue];
        self.keyboardHeight = keyboardFrame.size.height;
        
        self.height = self.topHeight + self.keyboardHeight;
    }
}

#pragma mark - 改变风格
- (void)setStyle:(ChatInputViewStyle)style
{
    switch (style) {
        case ChatInputViewStyleNormal:
            [self changeToNormalFromStyle:_style];
            break;
        case ChatInputViewStyleAudio:
            [self changeToAudioFromStyle:_style];
            break;
        case ChatInputViewStyleOther:
            [self changeToOtherFromStyle:_style];
            break;
        case ChatInputViewStyleText:
            [self changeToTextFromStyle:_style];
            break;
        case ChatInputViewStyleExpression:
            [self changeToExpressionFromStyle:_style];
            break;
        default:
            break;
    }
    
    _style = style;
}

- (void)changeToNormalFromStyle:(ChatInputViewStyle)style
{
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other"] forState:UIControlStateNormal];
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other_selection"] forState:UIControlStateHighlighted];

    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio"] forState:UIControlStateNormal];
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio_selection"] forState:UIControlStateHighlighted];
    
    self.buttonAudio.hidden = YES;
    self.textViewInput.hidden = NO;
    
    [self.textViewInput resignFirstResponder];
    
    self.height = self.topHeight;
    
    self.buttonOther.transform = CGAffineTransformMakeRotation(M_PI);
}

- (void)changeToAudioFromStyle:(ChatInputViewStyle)style
{
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other"] forState:UIControlStateNormal];
    [self.buttonOther setBackgroundImage:[UIImage imageNamed:@"chat_other_selection"] forState:UIControlStateHighlighted];
    
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_keyboard"] forState:UIControlStateNormal];
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_keyboard_selection"] forState:UIControlStateHighlighted];
    
    self.buttonAudio.hidden = NO;
    self.textViewInput.hidden = YES;
    
    [self.textViewInput resignFirstResponder];
    
    self.buttonOther.transform = CGAffineTransformMakeRotation(M_PI);
}

- (void)changeToOtherFromStyle:(ChatInputViewStyle)style
{
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio"] forState:UIControlStateNormal];
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio_selection"] forState:UIControlStateHighlighted];
    
    self.buttonAudio.hidden = YES;
    self.textViewInput.hidden = NO;
    
    [self.textViewInput resignFirstResponder];
    
    [self updateButtonFrame];
    
    self.buttonOther.transform = CGAffineTransformMakeRotation(M_PI/4);
}

- (void)changeToTextFromStyle:(ChatInputViewStyle)style
{
    self.buttonAudio.hidden = YES;
    self.textViewInput.hidden = NO;
    
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio"] forState:UIControlStateNormal];
    [self.buttonInput setBackgroundImage:[UIImage imageNamed:@"chat_audio_selection"] forState:UIControlStateHighlighted];
    
    self.buttonOther.transform = CGAffineTransformMakeRotation(M_PI);
    
    [self updateButtonFrame];
}

- (void)changeToExpressionFromStyle:(ChatInputViewStyle)style
{
    self.buttonAudio.hidden = YES;
    self.textViewInput.hidden = NO;
    
    [self.textViewInput resignFirstResponder];
    
    self.buttonOther.transform = CGAffineTransformMakeRotation(M_PI);
    
    [self updateButtonFrame];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (self.style == ChatInputViewStyleText || self.style == ChatInputViewStyleExpression) {
        CGSize newSize = [[change objectForKey:@"new"] CGSizeValue];
        CGSize oldSize = [[change objectForKey:@"old"] CGSizeValue];
        
        if (oldSize.height == newSize.height) {
            return;
        }
        
        if (newSize.height > 100) {
            [self.textViewInput scrollRangeToVisible:NSMakeRange(self.textViewInput.text.length - 1, 1)];
            return;
        }
        
        if (newSize.height < ChatInputView_Height) {
            self.animated = YES;
            self.textViewInput.height = 36;
        }else {
            self.animated = NO;
            self.textViewInput.height = newSize.height;
        }
        
        CGFloat bottomHeight = self.keyboardHeight;
        
        CGFloat height = bottomHeight + self.topHeight;
        
        self.top = self.superview.height - height;
        self.height = height;
        
        [self updateButtonFrame];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.textViewInput removeObserver:self forKeyPath:@"contentSize"];
    self.textViewInput = nil;
}

- (CGFloat)topHeight
{
    return self.textViewInput.height + 10;
}

- (void)updateButtonFrame
{
    self.buttonOther.bottom = self.textViewInput.bottom;
    self.buttonInput.bottom = self.textViewInput.bottom;
    self.buttonAudio.bottom = self.textViewInput.bottom;
}

- (void)resetButtonFrame
{
    self.buttonOther.centerY = self.height/2;
    self.buttonInput.centerY = self.height/2;
    self.buttonAudio.centerY = self.height/2;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    self.functionView.top = frame.size.height;
}

- (void)setDelegate:(id<ChatInputViewDelegate>)delegate
{
    _delegate = delegate;
    
    self.functionView.delegate = delegate;
}

#pragma mark - 录音
-(void)btnDown:(id)sender
{
    //创建录音文件，准备录音
    //语音文件配置
    //创建录音文件，准备录音
    //语音文件配置
    NSError *error = nil;
    BOOL result = [self.recordAudio recordWithError:&error conversionCompleteBlock:^(NSURL *filePath, NSError *error) {
        if (!error) {
            NSData *amrData = [NSData dataWithContentsOfURL:filePath];
            
            NSString *fileName = [FunctionMethod gen_uuid];
            NSString *wavPath = [[NSString alloc] initWithFormat:@"%@/%@.wav",[FunctionMethod audioDiretoryPath],fileName];
            NSURL *wavUrl = [NSURL fileURLWithPath:wavPath isDirectory:NO];
            BOOL ret = [MUPAudioUtility convertAmrFile:filePath toWavFile:wavUrl error:nil];
            
            if (ret) {
                NSInteger time = ceil([MUPAudioUtility wavDurationWithFilePath:wavUrl]);
                if ([self.delegate respondsToSelector:@selector(recordAudioUrl:audioData:audioLength:)]) {
                    [self.delegate recordAudioUrl:wavPath audioData:amrData audioLength:time];
                }
            }
        }
    }];
    
    if (!result) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:error.localizedDescription delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(beginRecord)]) {
        [self.delegate beginRecord];
    }
    
    self.recordView.hidden = NO;
    [self.superview bringSubviewToFront:self.recordView];
    
    self.detectTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
}

-(void)btnUp:(id)sender
{
    [self.detectTimer invalidate];
    self.detectTimer = nil;
    self.recordView.hidden = YES;
    
    double cTime = self.recordAudio.currentTime;
    if (cTime < 0.5) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"录音时间太短~" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        [self.recordAudio cancel];
        return;
    }
    
    [self.recordAudio stop];
}

-(void)btnDragUp:(id)sender
{
    [self.recordView showRecordCancel];
    self.recordView.hidden = NO;   
    [self.detectTimer invalidate];
    self.detectTimer = nil;
    [self.recordAudio pause];
    //    NSLog(@"取消发送录音");
}

-(void)btnDragEnter:(id)sender
{
    self.recordView.hidden = NO;
    if ([self.detectTimer isValid]) {
        [self.detectTimer invalidate];
        self.detectTimer = nil;
    }
    
    [self.recordAudio resume];
    
    self.detectTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
}

-(void)btnTouchUpOutside:(id)sender
{
    self.recordView.hidden = YES;
    [self.detectTimer invalidate];
    self.detectTimer = nil;
    [self.recordAudio cancel];
}

//定时检测触发方法
-(void)detectionVoice
{
    [self.recordAudio updateMeters];//刷新音量数据
    double lowPassResults = pow(10, (0.05 * [self.recordAudio peakPowerForChannel:0]));
    
    if (self.recordAudio.currentTime >= 60.0f) {
        [self btnUp:self.buttonAudio];
    } else {
        [self.recordView setVolumn:(NSInteger)floor(lowPassResults*10)];
    }
}

#pragma mark - 文本
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([@"\n" isEqualToString:text] == YES) {
        [self sendText:textView.text];
        textView.text = @"";
        return NO;
    }
    return YES;
}

#pragma mark - 表情代理
- (void)selectEmojiText:(NSString *)text
{    
    [self.textViewInput insertText:text];
}
    
- (void)sendClicked
{
    [self sendText:self.textViewInput.text];
    self.textViewInput.text = @"";
}

- (void)deleteClicked
{
    NSString *strText = self.textViewInput.text;
    if (strText.length > 0) {
        NSString *newStr;
        if (strText.length > 1) {
            newStr = [strText substringToIndex:strText.length - 2];
        }else {
            newStr = [strText substringToIndex:strText.length - 1];
        }
        
        self.textViewInput.text = newStr;
    }
}

- (void)sendText:(NSString *)text{
    if (![self checkText:text]) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(sendText:)]) {
        [self.delegate sendText:text];
    }
}

- (BOOL)checkText:(NSString *)text
{
    NSString *result = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (result.length == 0) {
        return NO;
    }
    return YES;
}
@end
